package com.ruix.app.ui.usercenter;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.ruix.app.R;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.UserMapper;
import com.ruix.app.model.User;
import com.ruix.app.model.UserInfo;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.ui.stratum.ReleasePostsActivity;
import com.ruix.app.ui.user.GenderChoseActivity;
import com.ruix.app.ui.user.address.ProvinceChoseActivity;
import com.ruix.app.util.ImageClipUtil;
import com.ruix.app.util.LogUitl;
import com.ruix.app.widget.dialog.fragment.ListDialogFragment;
import com.ruix.app.widget.dialog.iface.IListDialogListener;

import java.io.File;
import java.util.Calendar;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/5/4.
 */

public class UserConfigActivity extends BaseActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener,IListDialogListener{

    private TextView userNameView,userGenderView,userBirthdayView,
            userAddressView,userJobView,userCompanyView,userEmailView;
    private SimpleDraweeView userAvatar;
    private  User user;
    private int REQUEST_CODE_GENDER = 1000;
    private int REQUEST_CODE_NAME = 10001;
    private final int REQUEST_CODE_CAMERA = 222;

    private final int PHOTO_PICKED_WITH_DATA = 1002;
    private Uri cameraImgUri;
    private final int CAMERA_WITH_DATA = 1001;
    private final int ReQuestCode_CUT_PIC = 111;
    private final int DIALOG_REQUEST_CODE_SET_AVATAR = 0x02;

    @Override
    protected int loadViewLayout() {
        return R.layout.activity_user_config;
    }

    @Override
    protected void initView() {
        setTitle("个人信息");
        userAvatar =  (SimpleDraweeView)findViewById(R.id.iv_user_avatar);
        userGenderView =  (TextView)findViewById(R.id.tv_user_gender_value);
        userNameView =  (TextView)findViewById(R.id.tv_user_name_value);
        userBirthdayView =  (TextView)findViewById(R.id.tv_user_birthday_value);
        userAddressView =  (TextView)findViewById(R.id.tv_user_address_value);
        userJobView =  (TextView)findViewById(R.id.tv_user_job_value);
        userCompanyView =  (TextView)findViewById(R.id.tv_user_company_value);
        userEmailView =  (TextView)findViewById(R.id.tv_user_email_value);

    }

    @Override
    protected void initLocalData() {
        user = UserManager.getCurrentUser();
        userNameView.setText(user.getName());
        userAvatar.setImageURI(user.getAvatar());
        if (user.getGender() == 1){
            userGenderView.setText("男");
        } else {
            userGenderView.setText("女");
        }
        userBirthdayView.setText(user.getBirthday());
        userAddressView.setText(user.getLocate());
        userCompanyView.setText(user.getCompany());
        userJobView.setText(user.getPosition());
        userEmailView.setText(user.getEmail());
    }

    @Override
    protected void initListener() {
        findViewById(R.id.rl_user_avatar).setOnClickListener(this);
        findViewById(R.id.rl_user_gender).setOnClickListener(this);
        findViewById(R.id.rl_user_name).setOnClickListener(this);
        findViewById(R.id.rl_user_birthday).setOnClickListener(this);
        findViewById(R.id.rl_user_address).setOnClickListener(this);
        findViewById(R.id.rl_user_job).setOnClickListener(this);
        findViewById(R.id.rl_user_company).setOnClickListener(this);
        findViewById(R.id.rl_user_email).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_user_avatar:
                // 拍照或从相机选取  // TODO: 2017/5/5

                showDialog();
                break;
            case R.id.rl_user_gender:
                startActivity(GenderChoseActivity.newIntentModify(this,user.getGender()));
                break;
            case R.id.rl_user_name:
                startActivity(ModifyUserConfigActivity.newIntent(this,ModifyUserConfigActivity.TypeName));

                break;
            case R.id.rl_user_birthday:
                // 日期选择器
                showDatePicker();

                break;
            case R.id.rl_user_address:
                provinceChoose();
//                startActivity(ModifyUserConfigActivity.newIntent(this,ModifyUserConfigActivity.TypeLocation));
                break;
            case R.id.rl_user_job:
                startActivity(ModifyUserConfigActivity.newIntent(this,ModifyUserConfigActivity.TypePosition));
                break;
            case R.id.rl_user_company:
                startActivity(ModifyUserConfigActivity.newIntent(this,ModifyUserConfigActivity.TypeCompany));
                break;
            case R.id.rl_user_email:
                startActivity(ModifyUserConfigActivity.newIntent(this,ModifyUserConfigActivity.TypeEmail));
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initLocalData();
    }

    private void provinceChoose(){
        startActivityForResult(ProvinceChoseActivity.newIntent(this,""),2000);
    }

//    private String outputPath(){
//       return getExternalCacheDir().getAbsolutePath()+"avatar.png";
////    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 2000 && resultCode == 10013){
            if (data != null){
                String resion = data.getStringExtra("resion");
                saveUerInfo(resion,null);
            }
        } else if (requestCode == PHOTO_PICKED_WITH_DATA && resultCode == RESULT_OK){
            try {
                Uri originalUri = data.getData();
                Intent intent = new Intent(this, EditePictureActivity.class);
                intent.putExtra("uri", originalUri);
                intent.putExtra("picSource", "photo");
                startActivityForResult(intent, ReQuestCode_CUT_PIC);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == ReQuestCode_CUT_PIC) {

        } else if (requestCode == CAMERA_WITH_DATA && resultCode == RESULT_OK) {
            try {
                Intent intent = new Intent(this, EditePictureActivity.class);
                intent.putExtra("picSource", "camera");
                intent.putExtra("uri", cameraImgUri);
                startActivityForResult(intent, ReQuestCode_CUT_PIC);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == REQUEST_CODE_CAMERA){
            checkCameraPermission();
        }
    }


    private void saveUerInfo(String locate,String birthday){
        UserInfo userInfo = new UserInfo();
        userInfo.setLocate(locate);
        userInfo.setBirthday(birthday);
        showLoading();
        RequestFactory.editUserinfo(userInfo,new UserMapper(), new RXObserver<User>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(User value) {
                if (value != null && !TextUtils.isEmpty(value.getID())){
                    UserManager.sharedInstance().setCurrentUser(value);
                    UserManager.sharedInstance().saveCurrentUser();
                }

            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                showErrorTip(e.getMessage());
            }

            @Override
            public void onComplete() {
                dismissLoading();
                initLocalData();
            }
        });

    }

    private DatePickerDialog dialog;
    //生日
    private void showDatePicker(){
        final Calendar ca = Calendar.getInstance();
        int   mYear = ca.get(Calendar.YEAR);
        int  mMonth = ca.get(Calendar.MONTH) + 1;
        int mDay = ca.get(Calendar.DAY_OF_MONTH);
        dialog = new DatePickerDialog(this,this,mYear,mMonth,mDay);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        String birthday =  String.format("%d-%d-%d",year,month+1,dayOfMonth);
        saveUerInfo(null,birthday);
    }

    //选择照片
    private void showDialog(){
        String[] choosePic =new String[2];
        choosePic[0]= "照相";
        choosePic[1]= "从手机相册选择";
        ListDialogFragment.createBuilder(this)
                .setTitle("修改头像")
                .setPositiveButtonText(R.string.confirm)
                .setNegativeButtonText(R.string.cancel)
                .setItems(choosePic)
                .setSelectedItem(user.getGender())
                .setRequestCode(DIALOG_REQUEST_CODE_SET_AVATAR)
                .show();
    }


    private void getPhotograph() {
        Intent openAlbumIntent = new Intent(Intent.ACTION_PICK);
        openAlbumIntent.setDataAndType(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(openAlbumIntent,
                PHOTO_PICKED_WITH_DATA);
    }

    private void takePic() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// TODO: 16/5/26  没有外置存储
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            cameraImgUri = Uri.parse(Uri.fromFile(new File(ImageClipUtil.getCameraFileName(this))).toString());
            if (android.os.Build.VERSION.SDK_INT < 24) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImgUri);
            } else {
                //兼容android7.0 使用共享文件的形式
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, ImageClipUtil.getCameraFileName(this));
                Uri uri = getApplication().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                cameraImgUri = uri;
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            }
            startActivityForResult(intent, CAMERA_WITH_DATA);
        } else {
            showErrorTip("暂不支持");
        }
    }


    private void checkCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(UserConfigActivity.this, new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_CAMERA);
                return;
            } else {
                takePic();//调用具体方法
            }
        } else {
            takePic();//调用具体方法
        }
    }





    @Override
    public void onListItemSelected(CharSequence value, int number, int requestCode) {
        switch (requestCode) {
            case DIALOG_REQUEST_CODE_SET_AVATAR:
                if (number == 0) {
                    checkCameraPermission();
                } else {
                    getPhotograph();
                }
                break;
        }
    }

}
